package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
//import com.heima.model.article.pojos.ApArticle;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.ExceptionCatch.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.AdChannel;
import com.heima.model.wemedia.pojos.WmNews;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;



    @Override
    public void publishArticle(Integer newsId) {
        //1.根据文章id查询自媒体文章信息
        WmNews wmNews=getWmNews(newsId);
        //2.根据wmNews信息封装ApArticel对象
        ApArticle articel=ParseApArticel(wmNews);
        //3.保存修改apArticel对象
        saveOrUpdateApArticel(articel);
        //4.保存配置和内容信息
        saveConfigAndContent(articel,wmNews);
        //5.  页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),articel);
        //6.修改wmNews的状态设置为9并关联articelID
        upDateWmNews(wmNews,articel);
        //7.TODO  MQ通知es索引库更新文章索引
    }

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //校验参数
        Integer size = dto.getSize();
        if (size==null||size<=0){
            dto.setSize(10);
        }
        if (StringUtils.isBlank(dto.getTag())) {
            //推荐频道
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //调用mapper查询文章
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : apArticleList) {
            String images = apArticle.getImages();
            if (StringUtils.isNotBlank(images)){
                Arrays.stream(images.split(","))
                        .map(url->webSite+url)
                        .collect(Collectors.joining());
                apArticle.setImages(images);
            }
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        //分装返回方法
        return ResponseResult.okResult(apArticleList);
    }



    private void upDateWmNews(WmNews wmNews,ApArticle articel) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(articel.getId());
        wemediaFeign.updateWmNews(wmNews);
    }

    private void saveConfigAndContent(ApArticle articel, WmNews wmNews) {
        //保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(articel.getId());
        config.setIsComment(true);//是否允许评论
        config.setIsForward(true);//是否允许转发
        config.setIsDelete(false);//是否删除
        config.setIsDown(false);//是否下架
        apArticleConfigService.save(config);

        //保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(articel.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);

    }

    private void saveOrUpdateApArticel(ApArticle articel) {
        if (articel.getId()==null){
        //保存
            articel.setViews(0);
            articel.setLikes(0);
            articel.setComment(0);
            articel.setCollection(0);
            this.save(articel);
        }else {
            //删除之前关联的文章详情 文章配置信息
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getId,articel.getId())
            ); apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getId,articel.getId())
            );
        //修改
            this.updateById(articel);
        }
    }

    //基于wmNews封装Apaiticel
    private ApArticle ParseApArticel(WmNews wmNews) {
        //1.创建Articel将wmNews的属性拷贝过去
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        //2.单独设置articel字段
        apArticle.setId(wmNews.getArticleId());
        //3.其他需要补充字段 flag
        apArticle.setFlag((byte)0);
        apArticle.setLayout(wmNews.getType());
        //4.频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (channelResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        apArticle.setChannelName(channel.getName());
        //5.作者信息
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());
        return null;
    }

    private WmNews getWmNews(Integer newsId) {
        //1.根据id使用fegin接口调用
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        //拿到文章数据
        WmNews wmNews = result.getData();
        //2.判断文章是否为null
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章状态是否为4 或8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)
                &&WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        return wmNews;
    }
}